from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_restful import Resource, Api, reqparse
from bcat.gtp.serde.de.gtp_string_parser import GtpStringParser
from bcat.gtp.serde.ser.bytes_writer import BytesWriter
from bcat.gtp.serde.ser.pretty_printer import PrettyPrinter
from base64 import b64decode, b64encode
import binascii
import logging


app = Flask(__name__)
api = Api(app)


class GtpLint(Resource):
    def handle_gtp(self, gtp):
        return {'success': True}
    
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('gtp', type=str, required=True)
        args = parser.parse_args()

        logging.info(f"input gtp: {args['gtp']}")

        try:
            b_gtp = b64decode(args['gtp'], validate=True)
        except binascii.Error as e:
            return {'success': False, 'data': {'index': 0, 'message': f'Invalid base64 str: {e}'}}

        gtp = GtpStringParser().to_dict(b_gtp)
        if gtp is None:
            return {'success': False, 'data': {'index': 25, 'message': 'need an comma(,)'}}
            
        return self.handle_gtp(gtp)

class GtpPrettyPrint(GtpLint):
    def handle_gtp(self, gtp):
        writer = BytesWriter.default()
        PrettyPrinter(writer).serialize(gtp)
        pp = b64encode(writer.target()).decode()
        logging.info(f'pretty-print gtp: {pp}')
        return {'success': True, 'data': {'pretty_print': pp}}


api.add_resource(GtpLint, '/v1/gtp')
api.add_resource(GtpPrettyPrint, '/v1/gtp/pretty-print')


if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    app.run(debug=True, port=8002)
